package cn.tk.utils;

import cn.tk.exception.CustomException;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * Created by denglw on 2019/9/5.<br/>
 * Desc: javascript脚本引擎工具类
 */
public final class JsEngine {
    /**
     * 脚本引擎实例
     */
    private final ScriptEngine engine;

    private JsEngine() {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("javascript");
    }

    /**
     * 获取类对象实例.<br/>
     * @return 实例
     */
    public static JsEngine of() {
        return new JsEngine();
    }

    /**
     * 创建引擎绑定.<br/>
     * @return 绑定
     */
    public Bindings createBindings() {
        return engine.createBindings();
    }

    /**
     * 执行具体的脚本，返回执行的结果.<br/>
     * @param script js脚本
     * @return 执行结果
     */
    public Object eval(String script) {
        try {
            return engine.eval(script);
        } catch (ScriptException e) {
            throw new CustomException(e);
        }
    }

    /**
     * 执行具体的脚本，返回执行的布尔值.<br/>
     * @param script js脚本
     * @param bindings 绑定
     * @return 执行结果
     */
    public boolean evalBool(String script, Bindings bindings) {
        try {
            Object eval = engine.eval(script, bindings);
            if (eval instanceof  Boolean) {
                return (boolean) eval;
            }
            return false;
        } catch (ScriptException e) {
            throw new CustomException(e);
        }
    }

}
